package com.rockcent.mall.controller;

import com.rockcent.common.common.JsonResult;
import com.rockcent.common.common.RestDoing;
import com.rockcent.common.controller.BaseController;
import com.rockcent.common.domain.enumclass.Whether;
import com.rockcent.mall.Prop;
import com.rockcent.mall.Routes;
import com.rockcent.mall.lib.domain.*;
import com.rockcent.mall.lib.domain.enumclass.UploadFileBusinessType;
import com.rockcent.mall.lib.dto.MerchantStoreCustomerDto;
import com.rockcent.mall.lib.dto.QrCodeDto;
import com.rockcent.mall.lib.dto.UploadImageFileDto;
import com.rockcent.mall.lib.dto.UserInfoDto;
import com.rockcent.mall.lib.helper.BaseUserHelper;
import com.rockcent.mall.lib.helper.QRCodeHelper;
import com.rockcent.mall.lib.repository.*;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * Created by zhangjh on 2016/10/14.
 */
@RestController
public class MerchantStoreCustomerController extends BaseController {

    private final Logger log = LoggerFactory.getLogger(MerchantStoreCustomerController.class);

    @Autowired
    private BaseUserHelper userHelper;

    @Autowired
    private QRCodeHelper qrCodeHelper;

    @Autowired
    private MerchantStoreCustomerRepository merchantStoreCustomerRepository;

    @Autowired
    private MallRepository mallRepository;

    @Autowired
    private MerchantStoreRepository merchantStoreRepository;

    @Autowired
    private Prop prop;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;



    /**
     * @api {get} /merchant/store/customer/list 商家门店 核销员 列表
     * @apiGroup MERCHANT_STORE
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     * @apiParam {Long} storeId <code>必须参数</code> 门店ID
     * @apiSuccessExample {json} Success-Response:
     * {
     * "code": "1",
     * "desc": "成功",
     * "data": [
     * {
     *    "id": 3,
     *    "dateCreated": "2016-08-08 17:32:56",
     *    "lastUpdated": "2016-08-08 17:32:56",
     *    "version": 0,
     *    "verifyPersonId": 3,
     *    "storeId": 5,
     *    "nickName": "2 0n w"
     *  }
     *   ]
     * }
     */
    @RequestMapping(value = Routes.MERCHANT_STORE_CUSTOMER_LIST, method = RequestMethod.GET)
    public JsonResult merchantStoreCustomerList(MerchantStoreCustomerDto merchantStoreCustomerDto, HttpServletRequest request) {

        RestDoing doing = jsonResult -> {
            if(merchantStoreCustomerDto.getStoreId()==null){
                jsonResult.remind("storeId 不能为空",log);
                return;
            }
            List<MerchantStoreCustomer> result = this.merchantStoreCustomerRepository.findByStoreIdAndIsDelete(merchantStoreCustomerDto.getStoreId(),Whether.NO);
            jsonResult.data = result;

        };
        return doing.go(request, log);
    }

    /**
     * @api {put} /merchant/store/customer/delete 商家门店 核销员 删除
     * @apiGroup MERCHANT_STORE
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     * @apiParam {Long} id <code>必须参数</code> 核销员ID
     * @apiSuccessExample {json} Success-Response:
     * {
     * "code": "1",
     * "desc": "成功"
     * }
     */
    @Transactional
    @RequestMapping(value = Routes.MERCHANT_STORE_CUSTOMER_DELETE, method = RequestMethod.PUT)
    public JsonResult delMerchantStoreCustomer(@RequestBody  MerchantStoreCustomerDto merchantStoreCustomerDto, HttpServletRequest request) {

        RestDoing doing = jsonResult -> {
            if(merchantStoreCustomerDto.getId()==null){
                jsonResult.remind("ID 不能为空",log);
                return;
            }
            MerchantStoreCustomer result = this.merchantStoreCustomerRepository.findOne(merchantStoreCustomerDto.getId());
            result.setIsDelete(Whether.YES);
            merchantStoreCustomerRepository.saveAndFlush(result);

        };
        return doing.go(request, log);
    }

    /**
     * @api {put} /merchant/create/verifier/code 商家门店 生成绑定核销员二维码
     * @apiGroup MERCHANT_STORE
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     *
     * @apiParam {Long} storeId <code>必须参数</code> 门店id
     *
     * @apiSuccess data 返回二维码base64位编码格式 页面显示格式为:
     *
     * @apiSuccessExample {json} Success-Response:
     * {
     *  "code": "1",
     *  "desc": "成功",
     *  "data": "JRgABAgAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJ"
     * }
     */
    @Transactional
    @RequestMapping(value = Routes.MERCHANT_CREATE_VERIFIER_CODE, method = RequestMethod.PUT)
    public JsonResult createVerifierCode(HttpServletRequest request, @RequestBody  MerchantStoreCustomerDto dto){
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing =  jsonResult -> {
            if (dto.getStoreId() == null) {
                jsonResult.remind("门店ID 不能为空",log);
                return;
            }

            MerchantStore merchantStore = merchantStoreRepository.findByIdAndMerchantIdAndMallIdAndIsDelete(dto.getStoreId(), userInfoDto.merchant.getId(), userInfoDto.mall.getId(), Whether.NO);
            if (merchantStore == null) {
                jsonResult.remind("商家店面不存在, 请联系开发人员",log);
                return;
            }

            Mall mall = mallRepository.findOne(userInfoDto.mall.getId());
            if (mall == null) {
                jsonResult.remind("平台不存在, 请联系开发人员",log);
                return;
            }

            String host = mall.getCustomerClientDomain();
            if (StringUtils.isBlank(host)) {
                host = mall.getMobileHostName();
            }

            String verifyKey = DigestUtils.md5Hex(MerchantStoreCustomer.REDIS_SAVE_STORE_CUSTOMER_PREFIX + mall.getId() + userInfoDto.merchant.getId() + new Date().getTime());
            StringBuffer url = new StringBuffer();
            url.append("http://").append(host)
                    .append("?verifyKey=").append(verifyKey)
                    .append("&merchantId=").append(userInfoDto.merchant.getId())
                    .append("&storeId=").append(dto.getStoreId());
            String qrcCodeUrl = qrCodeHelper.createBase64QRCode(url.toString());
            stringRedisTemplate.opsForValue().set(verifyKey, String.valueOf(userInfoDto.merchant.getId()));
            stringRedisTemplate.expire(verifyKey, 1, TimeUnit.MINUTES);// 一分钟之内有效
            jsonResult.data = qrcCodeUrl;
        };
        return doing.go(request, log);
    }
}
